// ==UserScript==
// @name        YE功能增强.05 - [钱宝网]
// @description 支持钱包双击自动换算为人民币、批量打开任务、计算收益率等
// @namespace   http://AsionTang.CN
// @copyright   2013+, AsionTang
// @author      AsionTang
// @version     171008.18.03.048
// @iconURL     https://www.qbao.com/favicon.ico
// @downloadURL https://gitee.com/AsionTang/52.ScriptLibrary/raw/master/YeJS/05.QianBao.user.js
// @match       *://*.qianbao666.com/*
// @match       *://*.qbao.com/*
// @match       *://service.weibo.com/share/share.php*
// @grant       GM_openInTab
// @grant       GM_setClipboard
// ==/UserScript==

//为了安全的隔离，插件runtime和网页runtime，需要用自己的命名空间包裹起来。
var YeScript = YeScript || {};

//自动四舍五入指定位数，并去掉末尾的0占位符
Number.prototype.toFixedEx = function(n) {
    return this.toFixed(n).replace(/(\.?[0]+$)/g, '');
}

//将字符串里的千分符自动去掉并转换为Number对象
String.prototype.toNumber = function() {
    return Number(this.replace(/[^\d]/g, ''));
}

//将钱宝自动换算成RMB
window.YENewCount = function(countStr) {
    var count = countStr;
    if (isNaN(countStr)) {
        count = countStr.toNumber();
        if (isNaN(count))
            return countStr;
    }
    return '(' + (count / 100).toFixedEx(6) + '元)';
    // + countStr;
}
;

(function() {
    if (window.location.pathname != '/voucher/voucher.html')
        return;
    //================================================================
    // 18.支持自动添加宝券收入记录到随手记的功能.
    //================================================================
    document.onclick = function() {
        //不要重置掉此Click事件,以便在翻页时局部刷新列表后,还能够支持绑定事件.
        //document.onclick = null;
        console.log("18.支持自动添加宝券收入记录到随手记的功能. - 绑定触发事件.");
        var items = document.getElementsByTagName('tr');
        for (var i = 1; i < items.length; i++) {
            var item = items[i];
            item.ondblclick = function(e) {
                //一直向上获取指定Tag标签的父节点
                function getParentElementByTagName(e, tagName) {
                    if (e.tagName.toUpperCase() == tagName.toUpperCase())
                        return e;
                    if (e.parentElement == null)
                        return null;
                    return getParentElementByTagName(e.parentElement, tagName);
                }
                var tr = getParentElementByTagName(e.srcElement, 'TR');

                //(添加钱宝网宝券收入记录)
                var category = "3102391133";
                var account = "264209327";

                //钱宝券
                var price = (tr.children[2].innerText.toNumber() / 100).toFixedEx(2);
                var time = tr.children[1].innerText;
                var memo = tr.children[3].innerText;

                //拼接请求网址
                var url = 'https://money.feidee.com/money/tally/new.do?income#';
                url += category + ',';
                url += account + ',';
                url += price + ',';
                url += encodeURIComponent(time) + ',';
                url += encodeURIComponent(memo) + ',';
                console.log(url);

                GM_openInTab(url, {
                    insert: false,
                    active: false
                });
            }
        }
    }
}
)();

(function() {
    if (window.location.pathname != '/assetDetail/assetDetail.html')
        return;
    //================================================================
    // 17.支持自动添加收入记录到随手记的功能.
    //================================================================
    document.onclick = function() {
        //不要重置掉此Click事件,以便在翻页时局部刷新列表后,还能够支持绑定事件.
        //document.onclick = null;
        console.log("17.支持自动添加收入记录到随手记的功能. - 绑定触发事件.");
        var items = document.getElementById('detailTable').getElementsByTagName('tr');
        for (var i = 1; i < items.length; i++) {
            var item = items[i];
            item.ondblclick = function(e) {
                //一直向上获取指定Tag标签的父节点
                function getParentElementByTagName(e, tagName) {
                    if (e.tagName.toUpperCase() == tagName.toUpperCase())
                        return e;
                    if (e.parentElement == null)
                        return null;
                    return getParentElementByTagName(e.parentElement, tagName);
                }
                var tr = getParentElementByTagName(e.srcElement, 'TR');

                //(添加钱包网收入记录)
                var category = "20515976212";
                var account = "15722972730";

                //钱宝网
                var price = tr.children[3].innerText == '0.00' ? tr.children[4].innerText : tr.children[3].innerText;
                var time = tr.children[1].innerText;
                var memo = tr.children[2].innerText;

                //拼接请求网址
                var url = 'https://money.feidee.com/money/tally/new.do?income#';
                url += category + ',';
                url += account + ',';
                url += (price.toNumber()/100).toFixedEx(2) + ',';
                url += encodeURIComponent(time) + ',';
                url += encodeURIComponent(memo) + ',';
                console.log(url);

                GM_openInTab(url, {
                    insert: false,
                    active: false
                });
            }
        }
    }
}
)();

(function() {
    if (window.location.pathname != '/rich-roulette.htm' || location.hash === '')
        return;
    //================================================================
    // 16.幸运大转盘自动抽奖
    //================================================================
    setTimeout(function() {
        document.getElementById('play').click();
        setTimeout(function() {
            location.reload();
        }, 1000 + Math.random() * 500);
    }, 1000 + Math.random() * 500);
}
)();

(function() {
    if (window.location.pathname != '/usercenter/rewardsDetails.html')
        return;
    //================================================================
    // 15.自动领取红包奖励
    //================================================================
    $('#batReceiveMonthly').unbind('click');
    var btn = document.getElementById('batReceiveMonthly');
    btn.value = '开启自动领取红包奖励脚本';
    btn.onclick = function(e) {
        btn.value = '停止自动领取红包奖励脚本';
        if (window.setTimeout_zdlqjl) {
            console.log('停止自动领取红包奖励脚本。' + window.setTimeout_zdlqjl)
            clearTimeout(window.setTimeout_zdlqjl);
            return;
        }
        console.log('开启自动领取红包奖励脚本中')
        window.ye_step = 0;
        window.setTimeout_zdlqjl = setTimeout(window.ye_zdlqjlFun = function() {
            //console.log('自动领取红包奖励脚本运行中……')
            try {
                if (window.ye_step != 1 && (document.getElementById('user_shadow') == null || document.getElementById('user_shadow').style.display == "none")) {
                    window.ye_step = 1;
                    console.log('1.点击第一个领取');
                    document.querySelector('#AllRecord .btnRedbag a').click();
                    clearTimeout(window.setTimeout_zdlqjl);
                    window.setTimeout_zdlqjl = setTimeout(window.ye_zdlqjlFun, 1000 + Math.random() * 100);
                } else if (window.ye_step != 2 && (document.getElementById('randomTask').style.display != "none")) {
                    window.ye_step = 2;
                    console.log('2.点击“去做任务');
                    document.querySelector('#randomTask .popBox a.mdConfirmBtn').click();
                    clearTimeout(window.setTimeout_zdlqjl);
                    window.setTimeout_zdlqjl = setTimeout(window.ye_zdlqjlFun, 1000 + Math.random() * 1000);
                } else if (window.ye_step != 3 && document.getElementById('startImgTask').style.display != "none" && document.getElementById('imgBtn').className.indexOf('disabled') == -1) {
                    window.ye_step = 3;
                    console.log('3.点击“领取奖励');
                    document.getElementById('imgBtn').click();
                    clearTimeout(window.setTimeout_zdlqjl);
                    window.setTimeout_zdlqjl = setTimeout(window.ye_zdlqjlFun, 1000 + Math.random() * 1500);
                } else if (window.ye_step != 4 && document.getElementById('finishTask').style.display != "none") {
                    window.ye_step = 4;
                    console.log('4.点击“关闭收益对话框');
                    document.querySelector('#finishTask .popClose').click();
                    clearTimeout(window.setTimeout_zdlqjl);
                    window.setTimeout_zdlqjl = setTimeout(window.ye_zdlqjlFun, 1000);
                } else {
                    window.ye_step = 5;
                    console.log('5.其它未知情况');
                    clearTimeout(window.setTimeout_zdlqjl);
                    window.setTimeout_zdlqjl = setTimeout(window.ye_zdlqjlFun, 1000);
                }
            } catch (e) {
                clearTimeout(window.setTimeout_zdlqjl);
                console.log('自动领取红包奖励脚本出现异常：')
                console.dir(e);
            }
        }
        , 1000);
    }
}
)();

(function() {
    if (location.href.indexOf('service.weibo.com/share/share.php') == -1 || location.href.indexOf('qbao') == -1)
        return;
    //================================================================
    // 14.自动关闭弹出的SINA分享界面
    //================================================================
    //Chrome浏览其中，关闭窗口js无效.(window.close()) - sunxuezhi322 - 博客频道 - CSDN.NET
    //http://blog.csdn.net/sxzlc/article/details/7588704
    window.open('', '_self', '');
    window.close();
}
)();

(function() {
    if (window.location.pathname.indexOf('/user/task/joinedAgent') == -1)
        return;
    //================================================================
    // 13.批量做分销任务
    //================================================================
    var allTimeOut = 0;
    document.ye_i = 0;
    document.ondblclick = function() {
        var items = document.querySelectorAll('#data-table-body .process-btn');
        for (; document.ye_i < items.length; ) {
            document.ye_i = document.ye_i + 1;
            var item = items[document.ye_i];
            var text = item.parentElement.previousElementSibling.innerText;
            if (text.indexOf('已完成') > -1)
                continue;
            //
            var url = 'https://agent.qbao.com/user/task/seeProgress?isSettled=0&taskType=0&siteMenus=11&userFxId=' + item.dataset['id'];
            console.log(url);

            GM_openInTab(url, {
                insert: false,
                active: false
            });

            allTimeOut += Math.random() * 1000 + 1000;

            setTimeout(document.ondblclick, allTimeOut);
            break;
        }
    }
}
)();

(function() {
    //================================================================
    // 12.在分销界面自动点击任务功能
    //================================================================
    if (window.location.pathname != '/user/task/seeProgress')
        return;
    var isDoing = false;
    setInterval(function() {
        var item = document.querySelector('#study-dialog .md_pop .progress-bar');
        if (item && item.style.width != '' && item.style.width != '100%') {
            isDoing = false;
            return;
        }
        if (isDoing)
            return;
        //自动点击开始学习
        var items = document.querySelectorAll('.step-btn.active');
        if (items && items.length > 0) {
            isDoing = true;
            items[0].click();
            console.log('自动点击下一步中');
            return;
        }
        //第5步:点击继续任务
        var item = document.querySelector('#checkin-dialog .md_pop .continue-btn');
        if (item && item.className.indexOf('hidden') == -1) {
            item.click()
            console.log('第5步:点击继续任务');
            return;
        }
        //第4步:点击每日打卡
        var items = document.querySelectorAll('#checkin-dialog .md_pop .checkin-icon');
        if (items && items.length > 0) {
            items[0].click();
            console.log('第4步:点击每日打卡');
            return;
        }
        //第4步:点击做任务（分销任务时，或者自定义任务时）
        var items = document.querySelectorAll('body > div.site_frame > div.site_frame_main > div > div.site_frame_cont > div.container > div.main > div.tasks > div.task-content > div.right-col > a');
        if (items && items.length > 0 && items[0].className.indexOf('disabled') == -1) {
            items[0].click();
            console.log('第4步:点击做任务');
            return;
        }
        //第3步:点击继续任务
        var items = document.querySelectorAll('#share-dialog .md_pop .first-share.hidden');
        if (items && items.length > 0) {
            document.querySelector('#share-dialog .md_pop .continue-btn').click();
            console.log('第3步:点击继续任务');
            return;
        }
        //第2步:点击新浪分享
        var items = document.querySelectorAll('#share-dialog .md_pop');
        if (!document.Ye_12_HadDone_2 && items && items.length > 0) {
            document.Ye_12_HadDone_2 = true;
            document.querySelector('#share-dialog .md_pop .share-to .xl.share-icon-btn').click();
            console.log('第2步:点击新浪分享');
            return;
        }
        //第1步:先点击"每日分享"
        var btnShare = document.getElementsByClassName('share-btn')[0];
        if (!document.Ye_12_HadDone_1 && btnShare.innerText.indexOf('继续') == -1 && btnShare.parentElement.className.indexOf('hidden') == -1) {
            document.Ye_12_HadDone_1 = true;
            btnShare.click();
            console.log('第1步:先点击"每日分享"');
            return;
        }
        var item = document.querySelector('.daily-task .checkin-btn');
        if (item && item.innerText.indexOf('已') == -1) {
            item.click();
            console.log('点击"每日打卡"');
            return;
        }
        var item = document.querySelector('.daily-task .btn.study-btn');
        if (item && item.innerText.indexOf('已') == -1) {
            item.click();
            console.log('点击"每日学习"');
            return;
        }
    }, 1000)
}
)();

(function() {
    if (window.location.pathname != '/agent/home')
        return;
    //================================================================
    // 11.通过分析分销大厅的HTML得到当前最新任务列表
    //================================================================
    //将字符串里的千分符自动去掉并转换为Number对象
    String.prototype.toNumber = function() {
        return Number(this.replace(/[^\d]/g, ''));
    }
    //通过把指定元素的第一个匹配的className返回
    function getFirstElement(ele, className) {
        var items = ele.getElementsByClassName(className);
        if (!items || items.length != 1) {
            console.error('找不到ClassName:' + className);
            return;
        }
        return items[0];
    }
    //通过正则表达式返回匹配的数字
    function getNumber(regEx, text) {
        var values = text.match(regEx);
        if (!values || values.length != 1) {
            //var values = regEx.exec(text);
            //if (!values || values.length != 2) {
            console.error('正则表达式匹配错误:' + '\n正则表达式:' + regEx + '\n待匹配文本:' + text);
            return;
        }
        return values[0].toNumber();
        //return values[1].toNumber();
    }
    function downloadAsCsv(text) {
        var blob = new Blob([text],{
            type: "text/csv;charset=UTF-8"
        });
        var aLink = document.createElement('a');
        aLink.href = URL.createObjectURL(blob);
        aLink.download = 'Ye.CSV';
        aLink.click();
    }
    document.ondblclick = function() {
        var csvRows = localStorage.getItem('Ye_csvRows');
        if (csvRows == null)
            csvRows = "";
        //
        var colNames = ["id", "days", "margins", "totalReward", "penalty", "taskName", "isNew", "oneDayNum", "totalNum", "showTime", "taskSeq", "nowShowDate", "cpaUrl"];
        //
        var rmbRegEx = '[^,\\.\\d]*([,\\.\\d]+)[^,\\.\\d]*元';
        var regEx_margins = new RegExp("(加盟费" + rmbRegEx + ")|(保证金" + rmbRegEx + ")","gm");
        var regEx_totalReward = new RegExp("(分销补贴" + rmbRegEx + ")|(工资" + rmbRegEx + ")","gm");
        var regEx_penalty = new RegExp("(违约金" + rmbRegEx + ")|(失败罚金" + rmbRegEx + ")","gm");
        var regEx_days = new RegExp("周期[^,\\d]*([,\\d]+)[^,\\d]*天","gm");
        var regEx_id = new RegExp("(\\d+)\\.","gm");
        //
        var tasks = document.querySelectorAll('#hallListId li');
        for (var i = 0; i < tasks.length; i++) {
            var task = tasks[i];
            var text = task.innerText;
            var url = task.children[0].href;
            if (url.indexOf('http') == -1)
                url = 'http://www.qbao.com' + url;
            var tastItem = {};
            var margins = tastItem['margins'] = getNumber(regEx_margins, text);
            //排除掉保证金为0的体验任务
            if (!margins || margins == 0)
                continue;
            tastItem['id'] = getNumber(regEx_id, url);
            tastItem['cpaUrl'] = url;
            tastItem['taskName'] = getFirstElement(task, 'hall_list_data_title').innerText;
            tastItem['totalReward'] = getNumber(regEx_totalReward, text);
            tastItem['penalty'] = getNumber(regEx_penalty, text);
            tastItem['days'] = getNumber(regEx_days, text);
            var row = "";
            for (var keyIndex in colNames) {
                var key = colNames[keyIndex];
                var value = tastItem[key];
                if (!value || value == null)
                    value = "";
                row += value + ",";
            }
            csvRows += row + "\n";
        }
        localStorage.setItem('Ye_csvRows', csvRows);
        var nextPage = document.querySelectorAll('#hallPageId .md_page_area_fore');
        if (!nextPage || nextPage.length == 0) {
            alert('找不到Next Page按钮');
            return;
        }
        if (nextPage[0].firstChild.className.indexOf('disable') == -1) {
            console.log('模拟点击下一页中');
            document.getElementById('hallListId').addEventListener('DOMNodeInserted', function(e) {
                console.log('DOMNodeInserted' + e.timestamp);
                //当点击下一页时，会直接修改当前HTML，触发多次DOMNodeInserted事件，所以只有在最后一个事件触发时，才算加载完毕。
                clearInterval(window.Ye_11_id);
                window.Ye_11_id = setInterval(function() {
                    console.log('YES可以执行了。')
                    clearInterval(window.Ye_11_id);
                    //当存在数据时，就自动触发，直到最后一页
                    if (localStorage.getItem('Ye_csvRows') != null)
                        document.ondblclick();
                }, 1000);
            }, false)
            nextPage[0].children[0].click();
            return;
        }
        if (csvRows.length == 0) {
            alert('没有需要导出的数据!');
            return;
        }
        if (!confirm('是否导出数据?\n数据长度为:' + csvRows.length))
            return;
        // if (typeof GM_setClipboard != "undefined" && GM_setClipboard != null )
        //     GM_setClipboard(csvHeader + "\n" + csvRows, {
        //         type: 'text',
        //         mimetype: 'text/plain'
        //     });
        // else
        //     console.log(csvHeader + "\n" + csvRows);
        var csvHeader = "";
        for (var key in colNames)
            csvHeader += colNames[key] + ",";
        downloadAsCsv(csvHeader + "\n" + csvRows);
        if (confirm('是否清空所有数据?'))
            localStorage.removeItem('Ye_csvRows');
    }
}
)();

(function() {
    if (window.location.pathname != '/ntask/home.html')
        return;
    //================================================================
    // 10.通过分析任务大厅的HTML得到当前最新任务列表
    //================================================================

    //将字符串里的千分符自动去掉并转换为Number对象
    String.prototype.toNumber = function() {
        return Number(this.replace(/[^\d]/g, ''));
    }
    ;
    //通过把指定元素的第一个匹配的className返回
    function getFirstElement(ele, className) {
        var items = ele.getElementsByClassName(className);
        if (!items || items.length != 1) {
            console.error('找不到ClassName:' + className);
            return;
        }
        return items[0];
    }
    //通过正则表达式返回匹配的数字
    function getNumber(regEx, text) {
        var values = text.match(regEx);
        if (!values || values.length != 1) {
            //var values = regEx.exec(text);
            //if (!values || values.length != 2) {
            console.error('正则表达式匹配错误:' + '\n正则表达式:' + regEx + '\n待匹配文本:' + text);
            return;
        }
        return values[0].toNumber();
        //return values[1].toNumber();
    }
    function downloadAsCsv(text) {
        var blob = new Blob([text],{
            type: "text/csv;charset=UTF-8"
        });
        var aLink = document.createElement('a');
        aLink.href = URL.createObjectURL(blob);
        aLink.download = 'Ye.CSV';
        aLink.click();
    }
    document.ondblclick = function() {
        var item = getFirstElement(document, 'taskHall-lists');
        var tasks = item.getElementsByClassName('taskEve');
        if (!tasks || tasks.length == 0) {
            alert('找不到taskHall-lists下的taskEve');
            return;
        }

        var csvRows = localStorage.getItem('Ye_csvRows');
        if (csvRows == null)
            csvRows = "";

        var colNames = ["id", "days", "margins", "totalReward", "penalty", "taskName", "isNew", "oneDayNum", "totalNum", "showTime", "taskSeq", "nowShowDate", "cpaUrl"];

        var regEx_margins = /保证金[^,\.\d]*([,\.\d]+)[^,\.\d]*元/gm;
        var regEx_totalReward = /[^,\.\d]*([,\.\d]+)[^,\.\d]*元奖励/gm;
        var regEx_penalty = /罚金[^,\.\d]*([,\.\d]+)[^,\.\d]*元/gm;
        var regEx_days = /天数[^,\d]*([,\d]+)[^,\d]*天/gm;
        var regEx_id = /(\d+)/gm;
        for (var i = 0; i < tasks.length; i++) {
            var task = tasks[i];
            var text = task.innerText;

            var url = task.parentElement.dataset.href;
            if (url.indexOf('http') == -1)
                url = 'http://www.qbao.com' + url;

            var tastItem = {};
            var margins = tastItem['margins'] = getNumber(regEx_margins, text);
            //排除掉保证金为0的体验任务
            if (!margins || margins == 0)
                continue;

            tastItem['id'] = getNumber(regEx_id, url);
            tastItem['cpaUrl'] = url;
            tastItem['taskName'] = getFirstElement(task, 'taskTitle').innerText;
            tastItem['totalReward'] = getNumber(regEx_totalReward, text);
            tastItem['penalty'] = getNumber(regEx_penalty, text);
            tastItem['days'] = getNumber(regEx_days, text);

            var row = "";
            for (var keyIndex in colNames) {
                var key = colNames[keyIndex];
                var value = tastItem[key];
                if (!value || value == null)
                    value = "";
                row += value + ",";
            }
            csvRows += row + "\n";
        }
        localStorage.setItem('Ye_csvRows', csvRows);

        var pageBar = document.getElementById('pages_pg_2');
        var spans = pageBar.getElementsByTagName('SPAN');
        var nextPage = spans[spans.length - 2];
        if (nextPage.title != "Next Page") {
            alert('找不到Next Page按钮');
            return;
        }
        if (nextPage.childElementCount != 0) {
            nextPage.children[0].click();
            return;
        }
        if (csvRows.length == 0) {
            alert('没有需要导出的数据!');
            return;
        }
        if (!confirm('是否导出数据?\n数据长度为:' + csvRows.length))
            return;

        // if (typeof GM_setClipboard != "undefined" && GM_setClipboard != null )
        //     GM_setClipboard(csvHeader + "\n" + csvRows, {
        //         type: 'text',
        //         mimetype: 'text/plain'
        //     });
        // else
        //     console.log(csvHeader + "\n" + csvRows);

        var csvHeader = "";
        for (var key in colNames)
            csvHeader += colNames[key] + ",";

        downloadAsCsv(csvHeader + "\n" + csvRows);

        if (confirm('是否清空所有数据?'))
            localStorage.removeItem('Ye_csvRows');
    }
    ;
    //当存在数据时，就自动触发，直到最后一页
    if (localStorage.getItem('Ye_csvRows') != null)
        setTimeout(document.ondblclick, 1000);
}
)();

//广告“任务”对象
function Mission(_title, _yj, _sy, _adCount, _dayCount, _minDay, _wfsy, _url) {
    this.title = _title;
    this.yj = _yj;
    this.sy = _sy;
    this.dayCount = _dayCount;
    this.adCount = _adCount;
    this.minDay = _minDay;
    this.wfsy = _wfsy;
    this.url = _url;
}

computeSignPercent();
function computeSignPercent() {
    if (window.location.pathname != '/payportal/main.html')
        return;
    //================================================================
    // 09.自动计算“每日签到收益”
    //================================================================
    window.computeSignPercent = setInterval(function() {
        console.log(window.computeSignPercent);

        var totlaAssets = document.querySelectorAll('.total-asset .num')[0].innerText.toNumber();
        console.log("所有资产:" + totlaAssets);
        if (isNaN(totlaAssets) || totlaAssets == 0) {
            console.log("找不到 所有资产");
            return;
        }

        var todaySign = document.querySelectorAll('.today-in .num')[0].innerText.toNumber();
        console.log("签到收益:" + todaySign);

        //需要减去今日签到的收益，以昨日的总资产来计算，才准确。
        totlaAssets = totlaAssets - todaySign;

        //计算万份收益、年化收益
        var percent = todaySign / totlaAssets * 100 * 100;
        var nhsy = percent * 365 / 100;

        //显示万份收益、年化收益
        var info = '万份:' + percent.toFixedEx(4) + '｜年化:' + nhsy.toFixed(2);

        console.log(info);
        clearInterval(window.computeSignPercent);

        //随便找了个地方展示出来了。
        document.querySelectorAll('.total-asset .lb')[0].innerText = info;

        //将信息拷贝到剪贴板
        GM_setClipboard(info, {
            type: 'text',
            mimetype: 'text/plain'
        });
    }, 1000);
}

unsafeWindow.ye = function() {
    //================================================================
    // 08.获取“所有任务列表”并稍做处理后生成“CSV格式文本”输出到命令行和剪贴板
    //================================================================

    var csvHeader = "";
    var csvRows = "";

    var colNames = ["id", "days", "margins", "totalReward", "penalty", "taskName", "isNew", "oneDayNum", "totalNum", "showTime", "taskSeq", "nowShowDate", "cpaUrl"];
    for (var key in colNames)
        csvHeader += colNames[key] + ",";

    function getTasks(startIndex, endIndex, whenOnSuccess) {
        $.ajax({
            type: "POST",
            url: "http://www.qbao.com/task/listTask.html",
            data: "iDisplayStart=" + startIndex + "&iDisplayLength=" + endIndex + "&orderByMargins=&orderByDays=&orderByReward=&orderByStar=&marginsBegin=&marginsEnd=&daysBegin=&daysEnd=&rewardBegin=&rawardEnd=&industryType=&province=&city=&videoType=0&iCould=0&sEcho=&task_type=&r=4.156402621883899",
            dataType: "json",
            success: whenOnSuccess
        });
    }

    getTasks(0, 1, whenGetAllCountSuccess);
    function whenGetAllCountSuccess(result) {
        var allCount = result.data.itotalRecords;
        console.log('获取到所有任务数量为：' + allCount);

        getTasks(0, allCount, whenOnSuccess);
        //getTasks(0, 2, whenOnSuccess);
    }

    function whenOnSuccess(result) {
        if (result.data.aaData.length == 0)
            console.dir(result);
        console.log(result.data.itotalRecords);

        //iDisplayLength: 200
        //iDisplayStart: 100
        //itotalDisplayRecords: 1988
        //itotalRecords: 1988

        var items = result.data.aaData;
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            var row = "";
            for (var keyIndex in colNames) {
                var key = colNames[keyIndex];
                var value = item[key];
                if (value === undefined)
                    continue;
                //console.log(key+":"+value);
                if (value == null)
                    value = "";
                else
                    value = isNaN(value) ? value.replace(/[\n,天秒]/g, '') : value;

                if (key == "cpaUrl") {
                    //过滤“体验任务”
                    if (value != "") {
                        row = "";
                        break;
                    }
                    value = 'http://www.qbao.com/ntask/adv/' + item['id'] + '.html';
                }
                row += value + ",";
            }
            if (row == "")
                continue;
            csvRows += row + "\n";
        }
        console.log('最终拼接后字符串长度为：' + csvRows.length);

        GM_setClipboard(csvHeader + "\n" + csvRows, {
            type: 'text',
            mimetype: 'text/plain'
        });
    }
}
;

moneyConverter();
function moneyConverter() {
    if (window.location.pathname != '/task/loadTask.html')
        return;
    //================================================================
    // 07.自动计算任务详情界面的万份收益
    //================================================================
    window.YEDoit = function(className) {
        var items = document.getElementsByClassName(className);
        for (var i = 0; i < items.length; i++) {
            var tmp = items[i].nextSibling;
            if (!tmp || tmp.textContent.indexOf('钱宝') == -1)
                continue;
            items[i].innerText = window.YENewCount(items[i].innerText);
        }
    }
    ;
    window.YEProfit = function() {
        var tablebox = document.getElementsByClassName('tablebox');
        if (tablebox.length == 0)
            return;

        tablebox = tablebox[0];
        var items = tablebox.getElementsByClassName('money2');

        //获取 收益（任务收益）
        var shouyi = tablebox.getElementsByClassName('money')[0].innerText / 100;
        if (isNaN(shouyi))
            return;

        //获取 成本（任务保证金）
        var cost = items[0].innerText / 100;

        var adCount = items[2].innerText.toNumber();
        var dayCount = items[3].innerText.toNumber();
        //获取 天数（任务天数=广告条数/每日可看条数）
        var time = adCount / dayCount;

        //计算日均收益 = 收益/100/天数
        var day = shouyi / time;
        //计算万份收益 = 日均收益 * 10000
        var w = day / cost * 10000;

        //通过 押金+数量+收益 组合成唯一ID，来匹配某一组广告！
        var id = items[0].innerText + "_" + items[2].innerText + "_" + tablebox.getElementsByClassName('money')[0].innerText;
        id = id.replace(/,/g, '');

        //记录某一组广告的收益值
        localStorage.setItem(id, w.toFixedEx(4));
        localStorage.setItem(id + "day", time);

        //记录该条URL对应的广告的详细内容
        var missions = JSON.parse(localStorage.getItem('YE'));
        if (!missions)
            missions = new Object();
        //获取任务ID
        var id = /id=(\d+).+/g.exec(window.location.search)[1];
        var title = document.querySelector('.main .taskFont h1').title;
        missions[id] = new Mission(title,cost,shouyi,adCount,dayCount,time,w,window.location.href);
        localStorage.setItem('YE', JSON.stringify(missions));

        //显示
        var td = items[3].parentElement.nextElementSibling;
        if (!td)
            console.error('广告类型为空！无法容日均值和万分收益值');
        else
            td.innerHTML = '<span class="money">'//

            + '耗时天数:' + time//

            + '<br>日均收益:' + day.toFixedEx(2)//

            + '<br>万份收益:' + w.toFixedEx(4)//

            + '</span>';
    }
    ;
    window.onload = document.ondblclick = function(e) {
        window.YEProfit();
        window.YEDoit('money');
        window.YEDoit('money2');
    }
    ;
}

batchOpenMission();
function batchOpenMission() {
    if (window.location.pathname != '/task/userTaskInProcess.html')
        return;
    //================================================================
    // 06.批量做任务
    //================================================================
    document.ondblclick = function() {
        var items = document.getElementsByClassName('operableBtn');
        if (items.length == 0) {
            console.log('找不到 做任务的 Class类');
            return;
        }
        if (!confirm("是否马上批量执行任务？"))
            return;
        var j = prompt('输入批量执行的任务数量（取消为不限制）：');
        //虽说不限制，但是还是为了不崩溃，限制15个，刚好一页就好嘞。
        if (j == "" || j == null)
            j = 15;

        var patt1 = /(\d+),(\d+)/;
        var patt2 = /\((\d+)\)/;
        for (var i = 0; i < items.length && j > 0; i++) {
            var item = items[i];
            var no = patt1.exec(item.href);
            if (no) {
                if (no[2] == 11)
                    GM_openInTab('http://www.qbao.com/user/toDoAdvTask.html?userTaskId=' + no[1], {
                        insert: false,
                        active: false
                    });
                else
                    GM_openInTab('http://www.qbao.com/task/doTask.html?id=' + no[1], {
                        insert: false,
                        active: false
                    });
            } else if (no = patt2.exec(item.href)) {
                GM_openInTab('http://task.qbao.com/user/activity/todo/' + no[1], {
                    insert: false,
                    active: false
                });
            }
            j--;
        }
    }
}

searchBank();
function searchBank() {
    if (window.location.pathname != '/wallet/bankCard.html')
        return;
    //================================================================
    // 05.支持检索银行卡绑定时需要设置的银行支行
    //================================================================
    document.ondblclick = function() {
        var key = prompt('输入要检索的关键字：');
        //虽说不限制，但是还是为了不崩溃，限制15个，刚好一页就好嘞。
        if (key == "" || key == null)
            return;
        var subBank = document.getElementById('subBank');
        var banks = subBank.children;
        for (var i = 0; i < banks.length; i++) {
            var bank = banks[i];
            if (bank.innerText.indexOf(key) != -1) {
                subBank.value = bank.value;
                break;
            }
        }
    }
    ;
}

batchAll();
function batchAll() {
    if (window.location.pathname != '/task/advertisement.html')
        return;
    //================================================================
    // 04.在任务列表里将所有可能的任务的万份收益显示出来
    //================================================================
    document.addEventListener('DOMSubtreeModified', function(e) {
        //console.dir(e);
        if (YeScript.timeoutId)
            clearTimeout(YeScript.timeoutId);
        YeScript.timeoutId = setTimeout(YeScript.batchAllNow, 250);
    });

    function batchAllNow() {
        var items = document.getElementById('advertisement').children;
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            var tmp = item.getElementsByClassName('money2');
            //忽略“体验任务”
            if (!tmp || tmp.length != 2)
                continue;
            var yj = tmp[0].innerText;
            if (yj.indexOf('(') > -1)
                return;
            tmp[0].innerText = window.YENewCount(yj);
            //logEx("任务押金：",yj);

            var adCount = tmp[1].innerText;
            //logEx("广告数量：",adCount);

            var shouYiEle = item.getElementsByClassName('money')[0];
            var shouYi = shouYiEle.innerText
            shouYiEle.innerText = window.YENewCount(shouYi);
            //logEx("任务收益：",shouYi);

            //通过 押金+数量+收益 组合成唯一ID，来匹配某一组广告！
            var id = yj + "_" + adCount + "_" + shouYi;
            id = id.replace(/,/g, '');

            //通过广告组ID来查找“万份受益”值
            var wfsy = localStorage.getItem(id);

            var url = item.getElementsByTagName('a')[0].href;

            //当没有真实数据时，开始预测“万份收益”
            if (!wfsy)
                wfsy = "<br/>?" + YeScript.estimateWfsy(yj, adCount, shouYi, url);
            else {
                wfsy += "<br/>天数：" + localStorage.getItem(id + "day");
                //判断是否有该任务ID，用该条任务的确切数据，来覆盖该组广告的值。
                var missions = JSON.parse(localStorage.getItem('YE'));
                if (missions) {
                    var id = /id=(\d+).+/g.exec(url)[1];
                    var ms = missions[id];
                    if (ms)
                        wfsy = ms.wfsy + "<br/>天数：" + ms.minDay;
                }
            }

            var ps = item.getElementsByTagName('p');
            ps[ps.length - 1].innerHTML = "万份收益：" + wfsy;
        }

        function estimateWfsy(yj, adCount, shouYi, url) {
            yj = yj.toNumber();
            adCount = adCount.toNumber();
            shouYi = shouYi.toNumber();
            for (var dayCount = 5; dayCount > 0; dayCount--) {
                //任务天数，保证刚好能做完广告数量。
                if (adCount % dayCount != 0)
                    continue;
                //获取 天数（任务天数）
                var time = adCount / dayCount;

                //计算日均收益 = 收益/100/天数
                var day = shouYi / time;

                //计算万份收益 = 日均收益 * 10000
                var w = day / yj * 10000;
                if (w <= 8.7 && w >= 5) {
                    //当存在收益大于指定值的，需要打开URL确认一下！
                    if (w > 7.9)
                        GM_openInTab(url, {
                            insert: false,
                            active: false
                        });
                    return w.toFixedEx(4) + "<br/>天数：" + time;
                }
            }
            return -1;
        }
    }
}

autoFinishNew();
function autoFinishNew() {
    if (window.location.pathname != '/user/toDoAdvTask.html' && window.location.hostname != "task.qbao.com")
        return;
    //================================================================
    // 03.自动关闭已经完成任务的窗体（新任务界面）
    //================================================================
    setInterval(function() {
        //======新版本分享任务
        var pop_share = document.getElementById('pop-share');
        if (pop_share && pop_share.style.display != "") {
            //Chrome浏览其中，关闭窗口js无效.(window.close()) - sunxuezhi322 - 博客频道 - CSDN.NET
            //http://blog.csdn.net/sxzlc/article/details/7588704
            window.open('', '_self', '');
            window.close();
            return;
        }
        var pop_finishedTask = document.getElementById('pop-finishedTask');
        if (pop_finishedTask && pop_finishedTask.style.display != "") {
            var finishBtn = pop_finishedTask.getElementsByClassName('pop-finishedBtn')[0];
            finishBtn.click();
            return;
        }
        var btns = document.getElementsByClassName('task_finishBtn');
        if (btns && btns.length > 0) {
            btns[0].click();
            return;
        }
        //======老版本任务
        var complete = document.getElementById('doTaskDiv');
        if (complete && complete.style.display != "") {
            //Chrome浏览其中，关闭窗口js无效.(window.close()) - sunxuezhi322 - 博客频道 - CSDN.NET
            //http://blog.csdn.net/sxzlc/article/details/7588704
            window.open('', '_self', '');
            window.close();
            return;
        }
        var p = document.getElementsByClassName('doTaskNext dn')[0];
        if (p) {
            var isOk = p.style.display;
            if (isOk != 'block')
                return;
            var btn = document.getElementById('doNexGroupTask');
            if (btn) {
                btn.click();
                return;
            }
        }
    }, 2000);
}

autoFinish();
function autoFinish() {
    if (window.location.pathname != '/task/doTask.html')
        return;
    //================================================================
    // 02.自动关闭已经完成任务的窗体
    //================================================================
    setInterval(function() {
        var btn = document.getElementById('finishButton');
        if (btn.innerText.indexOf('今天广告已完成') > -1 || btn.innerText.indexOf('广告任务已经完成') > -1) {
            //Chrome浏览其中，关闭窗口js无效.(window.close()) - sunxuezhi322 - 博客频道 - CSDN.NET
            //http://blog.csdn.net/sxzlc/article/details/7588704
            window.open('', '_self', '');
            window.close();
        } else if (btn.attributes.disabled.value == 'false')
            btn.click();
        //console.log('自动结束TickLog');
    }, 2000);
}

computeWfsyAdv();
function computeWfsyAdv() {
    if (window.location.pathname.indexOf('/ntask/adv/') == -1)
        return;
    //================================================================
    // 01.加载时自动计算广告任务的万份收益值
    //================================================================
    window.onload = document.ondblclick = function(e) {
        var allDays = $('#taskTotalNum').text() / $('#taskOneDayNum').text();
        var wfsy = $('#taskReward').text().toNumber() / allDays / $('#taskMargins').text().toNumber() * 10000;
        $('.fl .last').html("万份收益：" + wfsy.toFixed(4) + "<br/>耗时天数：" + allDays + "天");
    }
    ;
}
